using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PHSRAG.Insight21;
using PHSRAG.Insight21.Common;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Humans;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Insight21.Policy;
using PHSRAG.Security;
using PHSRAG.Utility;
using PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.InsightWebControls;




public partial class SSOAccessRouter : GridPage
{
    //Header and QueryString Keys and Values
    private const string strCtRemoteUserHeaderId = "ct_remote_user";//Can as well move this variable to app_code/Keys.cs or any other place.....
    private const string strTargetPageQueryStringName = "TARGET_PAGE";
    private const string strBudgetOverview = "BUDGET_OVERVIEW";
    private const string strProtocolDetails = "PROTOCOL_DETAILS";
    private const string strFundNumberQueryStringName = "FUND_NUMBER";
    private const string strProtocolNumberQueryStringName = "PROTOCOL_NUMBER";
    private const string strProtocolTypeQueryStringName = "PROTOCOL_TYPE";
    

    private string strCtRemoteUserId = "";
    private string strTargetPage = "";
    private string strFundNumber = "";
    private string strProtocolNumber = "";
    private string strProtocolType = "";
    private ICachePolicy _cachePolicy;

    //private RefreshDates ctrlRefreshDates;

    private const string ssoAccessRouterPageKey = "SSOAccessRouterPageKey_126DB7A0-CFB2-4eac-BE25-4C05E0859765";
    private const string SearchCriteriaKey = "searchCriteria_151FACBB-1E28-4b63-A751-E5C2ABDAD65B";
    public static string CurrentLevelKey = "currentLevel_151FACBB-1E28-4b63-A751-E5C2ABDAD65B";
    public static string CurrentModuleKey = "currentModule_151FACBB-1E28-4b63-A751-E5C2ABDAD65B";
    /// <summary>
    /// get the UserContext
    /// </summary>
    private UserContext CurrentUserContext
    {
        get
        {
            return _cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.PageCacheKey = ssoAccessRouterPageKey;
        base.OnInit(e);
        _cachePolicy = (PHSRAG.Insight21.Policy.ICachePolicy)Session[PHSRAG.Insight21.Policy.Names.CachePolicyKey];
        //ctrlRefreshDates = new RefreshDates();
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        
        strCtRemoteUserId = (null != Request.Headers[strCtRemoteUserHeaderId] ? Request.Headers[strCtRemoteUserHeaderId].ToString() : "");
        strTargetPage = (null != Request.QueryString[strTargetPageQueryStringName] ? Request.QueryString[strTargetPageQueryStringName] : "");

        if (Settings.GetKeyValue("LogIncomingRequestsToInsight", false))
        {
            //Logging the Request from Info-Ed
            try
            {
                int intInfoEdToInsightLogId = Convert.ToInt32(DataAccess.ExecuteScalar(DataAccess.ConnectionString, "SaveInfoEdToInsightLog",
                                                    DataAccess.BuildSqlParameterArray("@Id", SqlDbType.Int, 0,
                                                                                      "@RemoteUser", SqlDbType.VarChar, strCtRemoteUserId,
                                                                                      "@TargetPage", SqlDbType.VarChar, strTargetPage,
                                                                                      "@QueryString", SqlDbType.VarChar, Request.QueryString.ToString(),
                                                                                      "@Url", SqlDbType.VarChar, Request.Url.ToString()
                                                                                     )));
            }
            catch (Exception ex)
            {
                //Supressing the error as its not a show stopper.
            }
        }
        try
        {
            UserContext userContext = new UserContext(_cachePolicy);
            userContext.Load(DataAccess.GetConnectionString(), strCtRemoteUserId);
            userContext.Cache();
                
            if ("" != strTargetPage)
            {
                switch (strTargetPage.ToUpper())
                {
                    case strBudgetOverview:
                        strFundNumber = (null != Request.QueryString[strFundNumberQueryStringName] ? Request.QueryString[strFundNumberQueryStringName].ToString() : "");
                        if ("" != strFundNumber)
                        {
                            string strPath = Request.ApplicationPath + string.Format("/Agreements/AgreementsBudgetOverview.aspx");//?{0}={1}", strFundNumberQueryStringName, strFundNumber);
                            if (SetOutGoingCache_BudgetDetails(strFundNumber, strPath))
                                Response.Redirect(strPath);
                            else
                                lblStatus.Text = string.Format("You are not authorized to view the Fund # : {0}", strFundNumber);
                        }
                        break;
                    case strProtocolDetails:
                        strProtocolNumber = (null != Request.QueryString[strProtocolNumberQueryStringName] ? Request.QueryString[strProtocolNumberQueryStringName].ToString() : "");
                        strProtocolType = (null != Request.QueryString[strProtocolTypeQueryStringName] ? Request.QueryString[strProtocolTypeQueryStringName].ToString() : "");
                        if ("" != strProtocolNumber)
                        {
                            string strPath = Request.ApplicationPath + string.Format("/Research/ProtocolDetails.aspx?{0}={1}&{2}={3}", strProtocolNumberQueryStringName, strProtocolNumber, strProtocolTypeQueryStringName, strProtocolType);
                            if (SetOutGoingCache(strProtocolNumber, userContext.DomainUserId))
                                Response.Redirect(strPath);
                            else
                                lblStatus.Text = string.Format("You are not authorized to view the Protocol : {0}", strProtocolNumber);
                        }
                        break;
                }
            }
            else
            {
                throw new Exception("Target page is not specified.");
            }
        }
        catch (Exception ex)
        {
            lblStatus.Text = ex.Message;
        }

    }

    private bool SetOutGoingCache_BudgetDetails(string strFundNumber,string strPageName)
    {
        strPageName = "http://" + Request.ServerVariables["SERVER_NAME"] + strPageName;
        try
        {
            
            
            //Getting the FundId by using the FundNumber [acquired from the query string]
            DataTable dtFundId = DataAccess.GetDataTable(DataAccess.GetConnectionString(), "dbo.GetFundIdByFundNumberAndDomainUserId",
                                    DataAccess.BuildSqlParameterArray(
                                    "@domainUserId", SqlDbType.Int, CurrentUserContext.DomainUserId,
                                    "@FundNumber", SqlDbType.VarChar, strFundNumber));

            if (dtFundId.Rows.Count == 0)
                throw new Exception("Failed to load Financial Summary information.");

            int intFundId = (null != dtFundId.Rows[0][0] ? Convert.ToInt32(dtFundId.Rows[0][0]) : 0);
            int intAccessLevel = (null != dtFundId.Rows[0][1] ? Convert.ToInt32(dtFundId.Rows[0][1]) : 0);

            DataSet dataContainer = DataAccess.GetDataSet(DataAccess.GetConnectionString(),"dbo.GetFundIDsAndTotals", 
                                    DataAccess.BuildSqlParameterArray(
                                    "@domainUserId", SqlDbType.Int, CurrentUserContext.DomainUserId,
                                    "@SessionID", SqlDbType.VarChar, Session.SessionID));

            if (dataContainer.Tables.Count != 2)
                throw new Exception("Failed to load Financial Summary information.");

            DataRow sourceDataRow = (DataRow)dataContainer.Tables[0].Select(string.Format("FundID={0}", intFundId))[0];

            intAccessLevel = (null != sourceDataRow["AccessLevel"] ? Convert.ToInt32(sourceDataRow["AccessLevel"]) : 0);

            DataTable dtFundIdsAndTotals = new DataTable();
            dtFundIdsAndTotals = dataContainer.Tables[0].Clone();
            dtFundIdsAndTotals.Clear();
            dtFundIdsAndTotals.ImportRow(sourceDataRow);
            
            DataSet dsFundIdsAndTotals = new DataSet();
            dsFundIdsAndTotals.Tables.Add(dtFundIdsAndTotals);
            
            DataSet dsFinancialSummaryForFunds = DataAccess.GetDataSet(DataAccess.GetConnectionString(), "GetFinancialSummaryForFunds",
                                            DataAccess.BuildSqlParameterArray("@xml", SqlDbType.Text, dsFundIdsAndTotals.GetXml()));
            DataRow drDataRow = dsFinancialSummaryForFunds.Tables[0].Select(string.Format("FundID={0}", intFundId))[0];

            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.FundNumberKey, strFundNumber);
            outgoingData.Add(Keys.AgreementIdKey, Convert.ToInt32(drDataRow["AgreementId"]));
            outgoingData.Add(Keys.JournalStartDateKey, "01/01/1900");
            outgoingData.Add(Keys.RevenueStartDateKey, "1/1/1900");
            outgoingData.Add(Keys.JournalEndDateKey, refreshDates.GLPostAsOfDate.ToShortDateString());
            outgoingData.Add(Keys.RevenueEndDateKey, refreshDates.GLPostAsOfDate.ToShortDateString());
            outgoingData.Add(Keys.RevenueTotalKey, (null != drDataRow["Revenue"].ToString() ? drDataRow["Revenue"].ToString() : ""));
            outgoingData.Add(Keys.SalaryAsOfDateKey, refreshDates.SalaryAsOfDate.ToShortDateString());
            string budgetStartDate = (null != drDataRow["BudgetStartDate"] ? drDataRow["BudgetStartDate"].ToString() : "");
            outgoingData.Add(Keys.BudgetYearKey, (budgetStartDate == string.Empty) ? 0 : Convert.ToDateTime(budgetStartDate).Year);
            outgoingData.Add(PHSRAG.Insight21.InsightUtilities.Constants.AgreementsConstants.AccessRightsKey, intAccessLevel);// Convert.ToInt32(sourceDataRow["AccessLevel"]));
            outgoingData.Add(Keys.RefreshBudgetDetailDataKey, true);
            PrevailingPageCachePolicy.Cache(PHSRAG.Insight21.InsightUtilities.Constants.AgreementsConstants.AgreementDetailsKey, outgoingData);
            
            PHSRAG.Insight21.Policy.ICachePolicy cachePolicy = (PHSRAG.Insight21.Policy.ICachePolicy)Page.Session[PHSRAG.Insight21.Policy.Names.CachePolicyKey];
            cachePolicy.Cache(CurrentModuleKey, "Agreements");
            CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;
            if (searchContext == null)
            {
                searchContext = new CommonSearchContext(cachePolicy);
                searchContext.Cache();
            }

            ControlCollection controlCollection = new ControlCollection(this);
            TextBox txtFundID  = new TextBox();
            txtFundID.ID = "fundID";
            txtFundID.CssClass = "DataInput";
            txtFundID.Attributes["Label"] = "Fund #:";
            txtFundID.Text = (null != drDataRow["FundId"] ? drDataRow["FundId"].ToString() : "");
            controlCollection.Add(txtFundID);

            searchContext.GetSearchCriteria(strPageName, controlCollection);
       

            return true;
        }
        catch (Exception ex)
        {
            UserContext usercontext = CurrentUserContext;

            PHSRAG.Utility.ExceptionReport.WriteToEventLog("SSOAccessRouter.aspx.SetOutGoingCache_BudgetDetails: Failed to getRefreshDates", ex, true, PHSRAG.Utility.ExceptionReport.ReportType.Error);
            if (usercontext != null)
                PHSRAG.Utility.ExceptionReport.WriteToEventLog(string.Format(" for the logged in User {0}, {1} with username ({2})",
                    usercontext.LastName, usercontext.FirstName, usercontext.Username), ex, true, PHSRAG.Utility.ExceptionReport.ReportType.Error);
            throw new Exception("Error occured while trying to retrieve data");
        }
    }

    private bool SetOutGoingCache(string strProtocolNumber,int intDomainUserId)
    {
        try
        {
            DataTable dataContainer = DataAccess.GetDataTable(
                DataAccess.GetConnectionString(), "dbo.[GetProtocolDetailsByProtocolNumber]", DataAccess.BuildSqlParameterArray(
                "@protocolNumber", SqlDbType.VarChar, strProtocolNumber,
                "@domainUserId", SqlDbType.Int, intDomainUserId));
            

            if ((dataContainer != null) && (dataContainer.Rows.Count > 0))
            {
                Hashtable outgoingData = new Hashtable();
                outgoingData.Add(Keys.ProtocolIdKey, dataContainer.Rows[0][0]);
                outgoingData.Add(Keys.ProtocolProcessIdKey, dataContainer.Rows[0][1]);
                outgoingData.Add(Keys.ProtocolAccessKey, dataContainer.Rows[0][2]);
                PrevailingPageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
                return true;
            }
            return false;
           
        }
        catch (Exception ex)
        {
            UserContext usercontext = CurrentUserContext;

            PHSRAG.Utility.ExceptionReport.WriteToEventLog("SSOAccessRouter.aspx.SetOutGoingCache: Failed to get the Protocol Details", ex, true, PHSRAG.Utility.ExceptionReport.ReportType.Error);
            if (usercontext != null)
                PHSRAG.Utility.ExceptionReport.WriteToEventLog(string.Format(" for the logged in User {0}, {1} with username ({2})",
                    usercontext.LastName, usercontext.FirstName, usercontext.Username), ex, true, PHSRAG.Utility.ExceptionReport.ReportType.Error);
            throw new Exception("Error occured while trying to retrieve data");
        }
    }



   
}
